package com.turing.post.cardmanagement.impl;

import java.math.BigInteger;
import java.util.List;

import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.turing.post.cardmanagement.util.AdjustInOutStockOrderDetail;
import com.turing.post.cardmanagement.util.AdjustInOutStockOrderDetailDao;
import com.turing.post.util.GeneralDao;
import com.turing.post.util.PCPSApplicationException;

/**
 * 调整单明细管理
 * 
 * @author YangShuo
 * 
 */
@Stateless(mappedName = "cardmanagement.impl.AdjustInOutStockOrderDetailDaoImpl")
@Remote
@Local
public class AdjustInOutStockOrderDetailDaoImpl implements
		AdjustInOutStockOrderDetailDao {

	@PersistenceContext
	protected EntityManager _em;

	@Override
	public void insertAdjustInOutStockOrderDetail(
			AdjustInOutStockOrderDetail adjustInOutStockOrderDetail)
			throws PCPSApplicationException {
		GeneralDao.insert(_em, adjustInOutStockOrderDetail);
	}

	/**
	 * @根据AdjustInOutStockOrderId批量查询
	 * @param AdjustInOutStockOrderId
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<AdjustInOutStockOrderDetail> getAdjustInOutStockOrderDetail(
			BigInteger AdjustInOutStockOrderId) {

		String sql = "select * from AdjustInOutStockOrderDetail where AdjustInOutStockOrderId="
				+ AdjustInOutStockOrderId;
		Query query = _em.createNativeQuery(sql,
				AdjustInOutStockOrderDetail.class);
		return query.getResultList();
	}

	@Override
	public void deleteAdjustInOutStockOrderDetail(
			BigInteger adjustInOutStockOrderId) throws PCPSApplicationException {
		String sql = "delete from AdjustInOutStockOrderDetail where AdjustInOutStockOrderId="
				+ adjustInOutStockOrderId;
		Query query = _em.createNativeQuery(sql);
		query.executeUpdate();
	}
	/**
	 * 根据卡号段验证调整单明细中是否存在状态为未审核的
	 */
    public int IsCardSeq(String startseqno,String endseqno)throws PCPSApplicationException{
    	String batchNo="";
    	// 截取到Batchno
		if (startseqno.trim().length() < 18) {
			batchNo=startseqno.substring(0, 6);
		} else {
			batchNo=startseqno.substring(0, 12);
		}
    	String sql = "select nvl(count(*),0) from AdjustInOutStockOrderDetail where  BatchNo=?1 "
			      +" and CardStartSeqNo>=?2 and CardEndSeqNo<=?3 "
			      +" and AdjustInOutStockOrderId in (select AdjustInOutStockOrderId from AdjustInOutStockOrder where Status='0')";		

	    Query query = _em.createNativeQuery(sql);
	    query.setParameter(1,batchNo);
	    query.setParameter(2,startseqno);
	    query.setParameter(3,endseqno);
	    return Integer.parseInt(query.getSingleResult().toString());
    }
}
